<template>
  <div class="m-pagination flex justify-between" :class="alignClass">
    <div class="total-container">
      <a-space :size="8">
        <span>共</span>
        <span class="weight-600 font-color">{{ total }}</span>
        <span>条</span>
      </a-space>
    </div>
    <div>
      <a-pagination
        show-quick-jumper
        show-page-changer
        v-model:current="current"
        :total="total"
        :pageSize="page_size"
        :pageSizeOptions="['10', '20', '30', '40', '50']"
        @change="pageChange"
        @showSizeChange="sizeChange"
      />
    </div>
  </div>
</template>

<script lang="ts">
  import { computed, defineComponent, reactive, ref, watch } from 'vue'

  export default defineComponent({
    name: 'pagination',
    emits: ['pageChange', 'sizeChange', 'change', 'update:modelValue'],
    props: {
      modelValue: {
        type: Object,
        default () {
          return {
            page_no: 1,
            page_size: 10,
            total: 10
          }
        }
      },
      align: {
        type: String,
        default: 'center' // left | right
      }
    },
    setup (props: any, ctx: any) {
      const { emit } = ctx
      const modelValue = reactive(props.modelValue)
      const current = ref(modelValue.page_no)
      const total = ref(modelValue.total)
      const page_size = ref(modelValue.page_size)

      const pageChange = (page_no) => {
        modelValue.page_no = page_no
        emit('update:modelValue', modelValue)
        emit('change', page_no)
      }

      const sizeChange = (currentSize: number, page_size: number) => {
        modelValue.page_size = page_size
        modelValue.page_no = 1
        emit('update:modelValue', modelValue)
        emit('change', page_size)
      }

      watch(
        () => modelValue.total,
        (newVal) => {
          total.value = newVal
        }
      )
      watch(
        () => modelValue.page_size,
        (newVal) => {
          page_size.value = newVal
        }
      )
      watch(
        () => modelValue.page_no,
        (newVal) => {
          current.value = newVal
        }
      )

      const alignClass = computed(() => {
        return {
          ['align-' + props.align]: true
        }
      })
      return {
        page_size,
        total,
        current,
        pageChange,
        sizeChange,
        alignClass
      }
    }
  })
</script>
